package com.youdo.careyes.ui;

import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;

import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.youdo.careyes.R;
import com.youdo.careyes.databinding.ActivityMainBinding;
import com.youdo.careyes.model.CameraChangeEvent;
import com.youdo.careyes.receiver.StorageBroadcastReceiver;
import com.youdo.careyes.utils.AppUtil;
import com.youdo.careyes.utils.Constants;
import com.youdo.careyes.utils.SpUtil;
import com.youdo.careyes.utils.ToastUtil;
import com.youdo.helper.ConnectCallback;
import com.youdo.helper.UVCCameraHelper;
import com.youdo.service.BufferWrapper;

import org.greenrobot.eventbus.EventBus;

/**
 * 首页
 *
 * @author ljb
 * @date 2025.07.30
 * @email 568838953@qq.com
 * 1.批发10元的摄像头
 * Size(1920x1080@30,type:7)
 * Size(1280x720@30,type:7)
 * Size(800x600@30,type:7)
 * Size(640x480@30,type:7)
 * Size(640x360@30,type:7)
 * Size(1920x1080@5,type:5)
 * Size(1280x720@10,type:5)
 * Size(800x600@20,type:5)
 * Size(640x480@30,type:5)
 * Size(640x360@30,type:5)
 * 2.乐惜 LX-2405 的摄像头,手机可出图
 * Size(1920x1080@30,type:7)
 * Size(1280x720@30,type:7)
 * Size(800x600@30,type:7)
 * Size(640x480@30,type:7)
 * Size(1280x960@30,type:7)
 * Size(1280x1024@30,type:7)
 * Size(1024x768@30,type:7)
 * Size(320x240@30,type:7)
 * Size(640x480@30,type:5)
 * 3.乐惜 1080p磨砂无畸变的摄像头,低配手机不出图,高配手机可出图;(2025.10.20)
 * 4.USB Camera̒0(BC-250219-ZW)摄像头,手机可出图;(2025.10.27)
 * Size(2048x1536@30,type:7),
 * Size(1920x1080@30,type:7),
 * Size(1280x960@30,type:7),
 * Size(1280x720@30,type:7),
 * Size(640x480@30,type:7),
 * Size(640x360@30,type:7),
 * Size(320x240@30,type:7),
 * Size(1920x1080@5,type:5),
 * Size(1280x960@5,type:5),
 * Size(1280x720@10,type:5),
 * Size(640x480@30,type:5),
 * Size(640x360@30,type:5),
 * Size(320x240@30,type:5)
 */
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private final UVCCameraHelper mCameraHelper = UVCCameraHelper.getInstance();
    private static final boolean DEBUG = true;
    private NavController navController;
    private final StorageBroadcastReceiver mSDReceiver = new StorageBroadcastReceiver();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        com.youdo.careyes.databinding.ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        Log.v(TAG, "onCreate msg: 准备录制下一段视频 新建 11 :" + savedInstanceState);
        Log.v(TAG, "onCreate msg: 准备录制下一段视频 新建 222 :" + mCameraHelper);
        navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        int[] arr = SpUtil.getInstance().getResolution();
        mCameraHelper.setDebugMode(true)// 打印数据
                .setPreviewSize(arr[0], arr[1])// 分辨率
                .setSegmentPeriod(3)// 分段录制视频.10分钟一段
                .setAudioRecord(SpUtil.getInstance().getBoolean(Constants.VIDEO_SOUND_SW))// 分段录制视频.10分钟一段
                .addTextureView(binding.cameraView)// 大屏
                .setSaveRootPath(SpUtil.getInstance().getSavePath())// 设置保存路径
                .initUVCCamera(this, new ConnectCallback() {

                    /*
                     * 检测到USB设备
                     * 每次 register 后,检查到有usb设备都会执行
                     */
                    @Override
                    public void onCheckUsbDevice(UsbDevice device) {
                        if (DEBUG) Log.v(TAG, "onCheckUsbDevice:" + device);
                        mCameraHelper.openUVCCamera();
                        //ToastUtil.showLong("检测到" + (device != null ? device.getDeviceName() : "null"));
                    }

                    /**
                     * 打开USB设备(正常是第一个USB设备)
                     */
                    @Override
                    public void onOpenUsbDevice(UsbDevice device) {
                        // ToastUtil.showLong("USB设备已连接" + (device != null ? device.getDeviceName() : "null"));
                        mCameraHelper.recordVideo(true);
                    }

                    /**
                     * 关闭USB设备(拔掉USB设备)
                     */
                    @Override
                    public void onCloseUsbDevice(UsbDevice device) {
                        if (DEBUG) Log.v(TAG, "onCloseUsbDevice:退出应用");
                        Intent intent = new Intent("com.youdo.stop.my.app");
                        intent.putExtra("packages", getApplicationInfo().packageName);
                        sendBroadcast(intent);// 系统杀死应用
                        AppUtils.exitApp();
                    }

                    /**
                     * 设备是否可用
                     * 等价于 enableButtons(true);
                     */
                    @Override
                    public void onDeviceAvailable(boolean enable) {
                        if (DEBUG) Log.v(TAG, "onDeviceAvailable:" + enable);
                    }

                    /**
                     * 预览是否可用
                     * 等价于 setPreviewButton(true);
                     */
                    @Override
                    public void onPreviewAvailable(boolean enable) {
                        if (DEBUG) Log.v(TAG, "onPreviewAvailable:" + enable);
                        mCameraHelper.setOrientation(SpUtil.getInstance().getBoolean(Constants.CAMERA_HORIZONTAL) ? 1 : 0, 0);// 水平镜像
                        mCameraHelper.setOrientation(SpUtil.getInstance().getBoolean(Constants.CAMERA_VERTICAL) ? 1 : 0, 1);// 竖直镜像
                        //if (enable) {// 自动显示2个窗口
                        mCameraHelper.previewSurfaceView(enable);
                        mCameraHelper.previewTextureView(enable);
                        // }
                    }

                    /**
                     * 录像状态改变(0-手动开始录像,1-低电量停止录像,2-手动停止录像,3-自动录制下一段视频)
                     */
                    @Override
                    public void onCameraChange(int status, String msg) {
                        if (DEBUG) Log.v(TAG, msg + ",isRecording " + mCameraHelper.isRecording());
                        if (status == 1) {// 低电量导致停止录像
                            ThreadUtils.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtil.showShort("低电量!!停止录像！");
                                }
                            });
                        }
                        EventBus.getDefault().post(new CameraChangeEvent(status, msg));
                    }

                    /**
                     * 帧数据的回调(需要先设置 回调的帧格式 PixelFormat,<0 则不回调)
                     */
                    @Override
                    public void onFrameReceived(BufferWrapper data) {
                        if (DEBUG)
                            Log.v(TAG, "收到的数据 FrameId " + data.getFrameId() + ",Length " + data.getLength() + "," + ConvertUtils.bytes2HexString(data.getHb()));
                    }
                });
        if (DEBUG) Log.v(TAG, "获取录像的保存路径:" + mCameraHelper.getRecordPath());
        if (DEBUG) Log.v(TAG, "获取截屏的保存路径:" + mCameraHelper.getPicturePath());
        AppUtil.keepScreenOn(this, !SpUtil.getInstance().getBoolean(Constants.ALLOW_SCREEN_OFF));

        mCameraHelper.register();
        mSDReceiver.register(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.v(TAG, "onResume:");
    }

    @Override
    public void onPause() {
        Log.v(TAG, "onPause:");
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mCameraHelper.unregister();
        mSDReceiver.unregister(this);
        super.onDestroy();
    }

    @Override
    public boolean onSupportNavigateUp() {
        return super.onSupportNavigateUp();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.v(TAG, "onKeyDown: keyCode= " + keyCode);
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (!mCameraHelper.isConnected()) {
            finish();
            return;
        }
        if (navController != null) {
            int currentDestination = navController.getCurrentDestination().getId();
            if (currentDestination == R.id.FirstFragment) {
                Log.v(TAG, "moveTaskToBack:");
                moveTaskToBack(true);// 移动任务到后台，模拟按下Home键的效果
                return;
            }
        }
        Log.v(TAG, "onBackPressed:");
        super.onBackPressed();
    }
}